package game.rule;

import com.sghd.common.utils.json.JsonUtils;
import data.entity.GameLine;
import game.model.ChessType;
import game.model.Grid;
import game.model.Result;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 规则计算服务
 */
public class Rule {

    /** 定义线规则*/
    public static List<Integer[]> lines = new ArrayList<>();

    public static void init(List<GameLine> gameLines) {
        if (!lines.isEmpty()) {
            lines.clear();
        }
        for (GameLine gameLine : gameLines) {
            Integer[] line = JsonUtils.string2Array(gameLine.getLine(), Integer.class);
            lines.add(line);
        }
    }


    /**
     * 消除的连线
     * @param grids
     * @return
     */
    public static Result elimite(final Grid[] grids, Set<Integer> eliminated, long base) {
        Result result = new Result();
        List<Integer> lineEqe = new ArrayList<>();
        for (int lineIdx = 0; lineIdx < lines.size(); lineIdx++) {//处理连线
            lineEqe.clear();
            Integer[] idxs = lines.get(lineIdx);
            ChessType first = grids[idxs[0]].getChess();//每条线第一个元素
            lineEqe.add(idxs[0]);
            for (int idx = 1; idx < idxs.length; idx++) {
                Grid next = grids[idxs[idx]];//下一个元素
                if (first.equals(next.getChess()) || first.equals(ChessType.WILD) || next.getChess().equals(ChessType.WILD)) {
                    lineEqe.add(idxs[idx]);
                    if (first == ChessType.WILD) {
                        first = next.getChess();
                    }
                } else {
                    break;
                }
            }
            List<ChessType> chessTypes = lineEqe.stream().map(integer -> grids[integer].getChess()).collect(Collectors.toList());
            if (chessTypes.size() == 1 && chessTypes.get(0) == ChessType.WILD) {//中了5个WILD
                continue;
            }
            if (lineEqe.size() >= first.getLimit()) {//中线
                ChessType emitType = null;//被消除的元素类型
                for (Integer leqe : lineEqe) {
                    //计算得分
                    Grid emilite = grids[leqe];
                    emilite.setMark(true);//标记为消除
                    eliminated.add(leqe);
                    if (emitType == null && emilite.getChess() != ChessType.WILD) {//找到被消除的元素类型
                        emitType = emilite.getChess();
                    }
                }
                if (emitType == null) {//当前线上全部都是WILD
                    continue;
                }
                int bet = emitType.getRate(lineEqe.size());//元素个数对应的倍率
                long fen = bet * base;//当前这条线，得分
                result.added(lineIdx + 1, new ArrayList<>(lineEqe), fen);//记录
            }
        }
        return result;
    }

    public static int getSize() {
        return lines.size();
    }

}

